﻿using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;

namespace EventBus.RabbitMQ.Events
{
    public class RabbitMqBus : IQueueBus
    {
        private readonly IConnectionChannelPool _connectionChannelPool;

        public RabbitMqBus(IConnectionChannelPool connectionChannelPool)
        {
            _connectionChannelPool = connectionChannelPool;
        }

        public void Send<T>(IQueueEvent<T> message) where T : IQueueEvent
        {
            IModel channel = null;
            {
                try
                {
                    channel = _connectionChannelPool.Rent(); 
                    var props = channel.CreateBasicProperties();
                    props.Persistent = true;
                    var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message.EventData));
                    channel.BasicPublish(message.ExchangeName, message.RouteKey, props, bytes);
                }
                finally
                {
                    if (channel != null)
                    {
                        var returned = _connectionChannelPool.Return(channel);
                        if (!returned)
                        {
                            channel.Dispose();
                        }
                    }
                }
            }
        }
    }
}